import { Radio } from 'antd';
import { Button, Popup } from 'devextreme-react';
import DataGrid, { Editing } from 'devextreme-react/data-grid';
import notify from 'devextreme/ui/notify';
import React, { useCallback, useImperativeHandle, useRef, useState } from 'react';
import { useModel } from 'umi';
import { intl } from '../../../utils';
import { columnsMonth, columnsYear } from './devDataGird';
import './index.less';
import { getNbwltjListData, updateBB_ReportInter_zl } from './service';

const defaultPreM = [
  'PreM1',
  'PreM2',
  'PreM3',
  'PreM4',
  'PreM5',
  'PreM6',
  'PreM7',
  'PreM8',
  'PreM9',
  'PreM10',
  'PreM11',
  'PreM12',
];
const defaultM = ['M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'M10', 'M11', 'M12'];

const defaultPreQ = ['PreQ1', 'PreQ2', 'PreQ3', 'PreQ4'];
const defaultQ = ['Q1', 'Q2', 'Q3', 'Q4'];

const defaultPreHY = ['PreHY1', 'PreHY2'];
const defaultHY = ['HY1', 'HY2'];

const defaultPreY = ['PreY1', 'PreY3', 'PreY5', 'PreY6', 'PreY7', 'PreY9', 'PreY10'];
const defaultY = ['Y1', 'Y3', 'Y5', 'Y6', 'Y7', 'Y9', 'Y10'];

const PupopColumnAdjust = React.forwardRef((props: any, ref: any) => {
  const { reloadDevTable } = props;
  const { initialState } = useModel('@@initialState');
  const { dbname } = (initialState?.curPart as API.CurPart) || {};
  const [visible, setVisible] = useState<boolean>(false);
  const popupRef = useRef<any>(null);
  const refsDevLeft = useRef<any>(null);
  const refsDevRight = useRef<any>(null);
  // const eventsSaveData = useRef<any>([]);
  const [selectedLeftData, setSelectedLeftData] = useState<any[]>([]);
  const [selectedRightData, setSelectedRightData] = useState<any[]>([]);
  const [radioValue, setRadioValue] = useState<number>(1);
  const [reviewState, setReviewState] = useState<number>(999);
  const [colYearData, setColYearData] = useState<any[]>([]);
  const [colMonthData, setMonthData] = useState<any[]>([]);
  const [selectClassName, setSelectClassName] = useState<any>('');

  const getDataList = useCallback(async (isQM: boolean) => {
    const res: any = await getNbwltjListData({
      dbname,
      isQM,
    });
    if (res.success) {
      let yearData;
      let monthData;
      let yearKey;
      let monthKey;
      if (isQM) {
        yearData = res.data.filter((el: { key: string }) => {
          return el.key[0].includes('Y');
        });
        monthData = res.data.filter((el: { key: string }) => {
          return !el.key[0].includes('Y');
        });
        yearKey = yearData
          .filter((el: any) => {
            return el.show;
          })
          .map((item: any) => item.key);
        monthKey = monthData
          .filter((el: any) => {
            return el.show;
          })
          .map((item: any) => item.key);
      } else {
        yearData = res.data.filter((el: { key: string }) => {
          return el.key[3].includes('Y');
        });
        monthData = res.data.filter((el: { key: string }) => {
          return !el.key[3].includes('Y');
        });
        yearKey = yearData
          .filter((el: any) => {
            return el.show;
          })
          .map((item: any) => item.key);
        monthKey = monthData
          .filter((el: any) => {
            return el.show;
          })
          .map((item: any) => item.key);
      }
      setSelectedRightData(yearKey);
      setSelectedLeftData(monthKey);
      setColYearData(yearData);
      setMonthData(monthData);
    }
  }, []);

  // 自定义方法
  useImperativeHandle(ref, () => ({
    showPupop: async (RadioData: any) => {
      setVisible(true);
      setRadioValue(RadioData);
      // setReviewState(3);
      setSelectClassName('ant-radio-button-wrapper-checked');
      await getDataList(RadioData === 1);
    },
  }));

  const onRadioChange = (e: any) => {
    setRadioValue(e.target.value);
    getDataList(e.target.value === 1);
    setReviewState(999);
  };

  const onCancel = () => {
    setVisible(false);
    setReviewState(999);
    setSelectedLeftData([]);
    setSelectedRightData([]);
  };

  const findData = (newData: any[], strKey: string) => {
    const isTrue = newData.find((itemF: any) => itemF === strKey);
    return isTrue;
  };

  const onOk = async () => {
    if (refsDevLeft.current) {
      if (selectedLeftData.length === 0 && selectedRightData.length === 0)
        return notify(`请选择账龄区间`, 'warning', 2000);
      const refsGridLeft = refsDevLeft.current.instance;
      let leftGetDataSource = refsGridLeft.getDataSource();
      const leftData = leftGetDataSource._items.map((item: any) => {
        item.rowState = 'update';
        item.where = { key: item.key };
        const newKey = findData(selectedLeftData, item.key);
        if (newKey) {
          item.show = true;
          return item;
        }
        item.show = false;
        return item;
      });
      const refsGridRight = refsDevRight.current.instance;
      let rightGetDataSource = refsGridRight.getDataSource();
      const rightData = rightGetDataSource._items.map((item: any) => {
        item.rowState = 'update';
        item.where = { key: item.key };
        const newKey = findData(selectedRightData, item.key);
        if (newKey) {
          item.show = true;
          return item;
        }
        item.show = false;
        return item;
      });
      const yearAndMonth = [...rightData, ...leftData];
      const res = await updateBB_ReportInter_zl(dbname, yearAndMonth);
      if (res.success) {
        onCancel();
        notify(`内部往来的账龄调整成功！`, 'success', 2000);
        reloadDevTable();
      } else {
        notify(`内部往来的账龄调整失败！${res.data}`, 'error', 2000);
      }
    }
  };

  const changeSelKey = (keySel: any) => {
    if (keySel === 1) {
      setSelectedLeftData(defaultM);
    } else if (keySel === 2) {
      setSelectedLeftData(defaultQ);
    } else if (keySel === 3) {
      setSelectedLeftData(defaultHY);
    } else {
      setSelectedLeftData(defaultHY);
      setSelectedRightData(defaultY);
    }
  };

  const changeSelKeyPre = (keySel: any) => {
    if (keySel === 1) {
      setSelectedLeftData(defaultPreM);
    } else if (keySel === 2) {
      setSelectedLeftData(defaultPreQ);
    } else if (keySel === 3) {
      setSelectedLeftData(defaultPreHY);
    } else {
      setSelectedLeftData(defaultPreHY);
      setSelectedRightData(defaultPreY);
    }
  };

  const onSelectionChangedLeft = useCallback(({ selectedRowKeys }: any) => {
    setSelectedLeftData(selectedRowKeys);
  }, []);

  const onSelectionChangedRight = useCallback(({ selectedRowKeys }: any) => {
    setSelectedRightData(selectedRowKeys);
  }, []);

  return (
    <>
      <Popup
        ref={popupRef}
        visible={visible}
        wrapperAttr={{
          class: 'fix-popup-title-width',
        }}
        title={'账龄调整'}
        {...props}
        width={500}
        // minWidth={'100%'}
        // maxWidth={501}
        height={600}
        // dragOutsideBoundary={true}
        resizeEnabled={true}
        onHiding={() => onCancel()}
        toolbarItems={[
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            size: 'small',
            options: {
              text: intl('pub.cancel', '取消'),
              onClick: () => onCancel(),
            },
          },
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            size: 'small',
            options: {
              text: intl('pub.ok', '确定'),
              type: 'default',
              onClick: () => onOk(),
            },
          },
        ]}
        contentRender={() => (
          <div>
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                marginBottom: 5,
              }}
            >
              <Radio.Group onChange={onRadioChange} value={radioValue}>
                <Radio value={1}>期末</Radio>
                <Radio value={2}>期初</Radio>
              </Radio.Group>
              <Button
                type="default"
                onClick={() => {
                  if (radioValue === 1) {
                    changeSelKey(6);
                  } else {
                    changeSelKeyPre(6);
                  }
                  setReviewState(999);
                }}
                text="恢复默认"
              />
            </div>
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                border: '2px solid #e3e3e3',
                borderRadius: 5,
              }}
            >
              <div style={{ borderRight: '2px solid #e3e3e3' }}>
                <div
                  style={{
                    margin: '10px 5px 10px 25px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                  }}
                >
                  月区间设置
                  <Radio.Group
                    buttonStyle="solid"
                    size="small"
                    className="antdRadioBtn"
                    // value={reviewState}
                    onChange={(e: any) => {
                      setSelectClassName('');
                      setReviewState(e.target.value);
                      if (radioValue === 1) {
                        changeSelKey(e.target.value);
                      } else {
                        changeSelKeyPre(e.target.value);
                      }
                    }}
                  >
                    <Radio.Button value={1}>月</Radio.Button>
                    <Radio.Button value={2}>季</Radio.Button>
                    <Radio.Button className={selectClassName} value={3}>
                      半年
                    </Radio.Button>
                  </Radio.Group>
                </div>
                <DataGrid
                  className="PaperDevSortableGrid devHeadersCenter"
                  width="240px"
                  height={380}
                  ref={refsDevLeft}
                  dataSource={colMonthData}
                  keyExpr="key"
                  defaultColumns={columnsMonth}
                  showBorders={false}
                  showRowLines={true}
                  showColumnLines={false}
                  repaintChangesOnly={true}
                  scrolling={{ mode: 'standard' }}
                  selectedRowKeys={selectedLeftData}
                  showColumnHeaders={false}
                  selection={{
                    mode: 'multiple',
                    // selectAllMode: 'allPages',
                    showCheckBoxesMode: 'always',
                  }}
                  onSelectionChanged={onSelectionChangedLeft}
                  // onSaved={saveDataLeft}
                >
                  <Editing mode="cell" allowUpdating={true} startEditAction="dblClick" />
                </DataGrid>
              </div>

              <div>
                <div style={{ margin: '10px 5px 10px 25px' }}>年区间设置</div>
                <DataGrid
                  className="PaperDevSortableGrid devHeadersCenter"
                  width="200px"
                  height={380}
                  ref={refsDevRight}
                  dataSource={colYearData}
                  keyExpr="key"
                  defaultColumns={columnsYear}
                  showBorders={false}
                  showRowLines={true}
                  showColumnLines={false}
                  repaintChangesOnly={true}
                  scrolling={{ mode: 'standard' }}
                  showColumnHeaders={false}
                  selectedRowKeys={selectedRightData}
                  selection={{
                    mode: 'multiple',
                    // selectAllMode: 'allPages',
                    showCheckBoxesMode: 'always',
                  }}
                  onSelectionChanged={onSelectionChangedRight}
                  // onSaved={saveDataRight}
                >
                  <Editing mode="cell" allowUpdating={true} startEditAction="dblClick" />
                </DataGrid>
              </div>
            </div>
          </div>
        )}
      />
    </>
  );
});

export default PupopColumnAdjust;
